<template>
    <div>
        <navbar :title="$t('set_pwd')">
            <template #right>
                <span class="write-btn-right font-size15 head-right" style="line-height: 56px;" v-if="oldPassword == '' && newPassword == '' && pwdConfirm == ''">{{ $t("save") }}</span><!--保存-->
                <span class="write-btn-right font-size15 cur head-right" style="line-height: 56px;font-weight: bold" v-debounce="() => onSubmit(false)" v-if="oldPassword !== '' || newPassword !== '' || pwdConfirm !== ''">{{ $t("save") }}</span><!--保存-->
            </template>
        </navbar>
        <div class="content-noBottom">
            <div class="pwd-userInfo">
                <div>
                    {{userInfo.usrSteUsrId}}
                </div>
            </div>
            <ul class="set-password-body bottom-shadow">
                <li>
                    <div class="set-password">
                        <span>{{ $t("set_pwd_old") }}</span><!--旧密码-->
                        <div v-focusInput:oldPassword>
                            <input :placeholder="$t('reset_pwd_old_tips')" v-validate="{required:true}"  v-model="oldPassword" name="oldPassword" :type="showPassword.old.format"><!--请输入旧密码-->
                            <i class="input-delete input-see" :class="{'cur' : showPassword.old.show}" @click="seePassword('old')">
                                <em></em>
                            </i>
                            <i class="input-delete">
                                <i></i>
                            </i>
                        </div>
                    </div>
                    <div @input="errorOld = false" class="colorfd3 font-size11" style="margin-top: -15px;" v-if="errorOld && !errors.has('oldPassword')">{{ errorsMessage }}</div>
                    <div class="colorfd3 font-size11" style="margin-top: -15px;">{{errors.first('oldPassword')}}</div>
                </li>
                <li>
                    <div class="set-password">
                        <span>{{ $t("set_pwd_new") }}</span><!--新密码-->
                        <div v-focusInput:newPassword>
                            <input :placeholder="$t('set_pwd_new_tips')" :type="showPassword.newp.format" @input="errorNew = false" v-validate="'required|usrPasswordCheck'" v-model="newPassword" name="newPassword"><!--请输入新的密码-->
                            <i class="input-delete input-see" :class="{'cur' : showPassword.newp.show}" @click="seePassword('newp')">
                                <em></em>
                            </i>
                            <i class="input-delete">
                                <i></i>
                            </i>
                        </div>
                    </div>
                    <div class="colorfd3 font-size11" style="margin-top: -15px;">{{errors.first('newPassword')}}</div>
                    <div class="colorfd3 font-size11" v-if="errorNew && newPassword !== ''" style="margin-top: -15px;">{{ errorsMessage }}</div>
                </li>
                <li>
                    <div class="set-password">
                        <span>{{ $t("set_pwd_confirm") }}</span><!--确认新密码-->
                        <div v-focusInput:pwdConfirm>
                            <input :placeholder="$t('set_pwd_new_again')" v-validate="{required: true, usrPasswordCheck: true, is: newPassword}" v-model="pwdConfirm" name="pwdConfirm" :type="showPassword.confirm.format"><!--请再次输入新密码-->
                            <i class="input-delete input-see" :class="{'cur' : showPassword.confirm.show}" @click="seePassword('confirm')">
                                <em></em>
                            </i>
                            <i class="input-delete">
                                <i></i>
                            </i>
                        </div>
                    </div>
                    <div class="colorfd3 font-size11" style="margin-top: -15px;">{{errors.first('pwdConfirm')}}</div>
                </li>
            </ul>
            <ul class="pwd-tips">
                <li><i class="remind-icon-2"></i>{{ $t("set_pwd_tips_one", { min: this.pwdMin, max: this.pwdMax }) }}</li><!--长度为3-20个字符-->
                <li><i class="remind-icon-2"></i>{{ $t("set_pwd_tips_two") }}</li><!--必须同时包含英文字母和数字-->
                <li><i class="remind-icon-2"></i>{{ $t("set_pwd_tips_three") }}</li><!--使用纯英文字母/数字/特殊字符的组合-->
                <li><i class="remind-icon-2"></i>{{ $t("set_pwd_tips_four") }}</li><!--不能使用空格、包含有非法字符-->
                <li v-if="passwordPolicyInfo.policyCompareCount !== ''"><i class="remind-icon-2"></i>{{ $t("set_pwd_tips_five", { min: this.pwdMin, max: this.pwdMax }) }}{{ passwordPolicyInfo.policyCompareCount }}{{ $t("set_pwd_tips_six") }}</li><!--新密码不能跟以往次历史密码一样-->
            </ul>
        </div>
        <div v-if="!passwordPolicyInfo.forceChange && isLateChange" class="sign-up" @click="back()">
            {{ $t("set_pwd_late_change") }}
        </div>
        <!--tips-->
        <!--密码修改成功！-->
        <van-dialog
            v-model="save"
            :confirm-button-text="$t('sure')"
            :title="$t('set_tip_pwd_update_success')"
            @confirm="$router.go(-1)"
            >
        </van-dialog>
        <div class="loading" v-if="saveLoading">
            <div >
                <div style="width: 33px;height: 33px;">
                    <img src="../../../static/images/loading.gif" alt="" style="width: 100%"/>
                </div>
                <div>{{ $t("saveing") }}</div><!--保存中...-->
            </div>
        </div>
    </div>
</template>

<script>
/*eslint-disable no-unused-vars*/
import {Toast} from 'vant';
import { clearLoginStorage } from '@/utils/tools';
import { encryptFun, randomString } from '@/utils/crypto';
let Base64 = require('js-base64').Base64;
export default {
    name: 'SetPassword',
    components: {Toast},
    data() {
        return {
            userInfo: {},
            newPassword: '',
            oldPassword: '',
            pwdConfirm: '',
            errorsMessage: '',
            errorNew: false,
            errorOld: false,
            save: false,
            passwordPolicyInfo: {}, //密码信息
            pwdMin: '',
            pwdMax: '',
            isShowBack: {backText: ''},
            setPassword: 'password',
            inputSee: false,
            isLateChange: false, //迟点再改
            saveLoading: false, //保存中
            notEmpty: false, //不为空
            showPassword: {
                old: {
                    format: 'password',
                    show: false
                },
                newp: {
                    format: 'password',
                    show: false
                },
                confirm: {
                    format: 'password',
                    show: false
                }
            }
        };
    },
    created() {
        // this.$Validator.extend('usrPasswordType', {
        //     validate(value) {
        //         return value.search(/[^a-zA-Z0-9_-]/) === -1;
        //     }
        // });
        this.$Validator.extend('usrPasswordCheck', {
            validate(value) {
                // 请使用纯英文字母/数字/特殊字符的组合 (必须同时包含大小写英文字母和数字以及特殊字符)。
                return /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_])/.test(value);
            }
        });
        this.$Validator.extend('confirmPassword', {
            validate(value) {
                return false;
            }
        });
        if (this.$route.query.isForceChange) {
            this.isShowBack = {showBack: false};
            this.isLateChange = true;
        }
    },
    methods: {
        confirm() {
            window.sessionStorage.clear();
            clearLoginStorage();
            this.$router.replace({path: '/'});
        },
        onSubmit() {
            if (this.newPassword.length < this.pwdMin || this.newPassword.length > this.pwdMax) {
                Toast(this.$t('set_tip_pwd_update_tips', { min: this.pwdMin, max: this.pwdMax }));
            } else {
                this.$validator.validate().then(result => {
                    if (result) {
                        const key = randomString(16);
                        this.saveLoading = true;
                        this.$axios({
                            method: 'POST',
                            url: `/app/api/trainee/my/user`,
                            data: {
                                oldPwd: key + encryptFun(this.oldPassword, key),
                                password: key + encryptFun(this.newPassword, key)
                            }
                        }).then(res => {
                            this.errorsMessage = res.data.errorMsg;
                            switch (res.data.errMsg) {
                            // case 'update_ok' ://更新成功
                            case 'success' ://更新成功
                                this.saveLoading = false;
                                this.save = true;
                                if (this.$route.query.isForceChange) {
                                    this.$router.replace({path: '/home'});
                                } else {
                                    this.save = true;
                                }
                                break;
                            case 'usr_password_has_existed' ://新密码和之前历史记录一样
                                this.saveLoading = false;
                                this.errorsMessage = this.$t('set_pwd_tips_five') + this.passwordPolicyInfo.policyCompareCount + this.$t('set_pwd_tips_six');//国际化用于有时语言不统一
                                this.errorNew = true;
                                break;
                            case 'usr_old_password_error' ://密码错误
                                this.saveLoading = false;
                                this.errorOld = true;
                                break;
                            case 'old_and_new_similar' ://旧密码和新密码一样
                                this.saveLoading = false;
                                this.errorNew = true;
                                break;
                            }
                        }).catch(err => {
                            if (err.response.data.errorMsg) {
                                this.errorsMessage = err.response.data.errorMsg;
                            } else {
                                this.errorsMessage = err.response.data.errMsg;
                            }
                            this.errorNew = true;
                            this.saveLoading = false;
                        });
                    }
                });
            }
        },
        seePassword(action) {
            if (action === 'old') {
                if (this.showPassword.old.format === 'password') {
                    this.showPassword.old.format = 'text';
                    this.showPassword.old.show = true;
                } else {
                    this.showPassword.old.format = 'password';
                    this.showPassword.old.show = false;
                }
            } else if (action === 'newp') {
                if (this.showPassword.newp.format === 'password') {
                    this.showPassword.newp.format = 'text';
                    this.showPassword.newp.show = true;
                } else {
                    this.showPassword.newp.format = 'password';
                    this.showPassword.newp.show = false;
                }
            } else if (action === 'confirm') {
                if (this.showPassword.confirm.format === 'password') {
                    this.showPassword.confirm.format = 'text';
                    this.showPassword.confirm.show = true;
                } else {
                    this.showPassword.confirm.format = 'password';
                    this.showPassword.confirm.show = false;
                }
            }
        },
        back() {
            this.$router.push({path: 'home'});
        }
    },
    directives: {
        'focusInput': {
            bind(el, binding, vnode) {
                let child = el.children;
                let input = child[0];
                let btnDelete = child[2];
                if (!input.value) {
                    btnDelete.style.visibility = 'hidden';
                }
                input.oninput = (e) => {
                    if (e.target.value) {
                        btnDelete.style.visibility = 'visible';
                    } else {
                        btnDelete.style.visibility = 'hidden';
                    }
                };
                input.onblur = (e) => {
                    if (!e.target.value) {
                        btnDelete.style.visibility = 'hidden';
                    }
                };
                btnDelete.onclick = (e) => {
                    binding.arg ? vnode.context[binding.arg] = '' : input.value = '';
                    btnDelete.style.visibility = 'hidden';
                };
            }
        }
    },
    mounted() {
        this.$axios({
            method: 'POST',
            url: '/app/api/trainee/user/passwordPolicyInfo'
        }).then(res => {
            this.passwordPolicyInfo = res.data;
            this.pwdMin = res.data.minLength;
            this.pwdMax = res.data.maxLength;
        });
        this.$axios({
            method: 'GET',
            url: '/app/api/user/current'
        }).then(res => {
            this.userInfo = res.data;
        });
    }
};
</script>

<style scoped lang="less">
    .set-password-body{
        background: #ffffff;
        li{
            height: 70px;
            background: #ffffff;
            margin-left: 15px;
            border-bottom: 1px solid #cccccc;
            .set-password{
                height: 60px;
                line-height: 16px;
                background: #ffffff;
                display: flex;
                align-items: center;
                span{
                    display: block;
                    width: 115px;
                }
                div{
                    height: 100%;
                    width: 100%;
                    display: flex;
                    input{
                        height: 100%;
                        width: calc(100% - 60px);
                        border: none;
                        font-size: 16px;
                        padding-left: 10px;
                    }
                }
            }
        }
        li:nth-last-child(1) {
            border-bottom: none;
        }
    }
    .input-delete {
        width: 25px;
    }
    .input-see {
        width: 30px;
        margin-right: 5px;
        em {
            width: 20px;
            height: 20px;
            display: inline-block;
            background: url(../../../static/images/browse-icon.png) no-repeat 0 -22px;
            background-size: 20px;
        }
        &.cur {
            em {
                background-position: 0 -46px;
            }
        }
    }
    .pwd-userInfo{
        background: #ffffff;
        height: 50px;
        display: flex;
        align-items: center;
        padding-left: 15px;
        margin: 40px 0 40px;
    }
    .pwd-tips{
        margin-top: 20px;
        li{
            padding-left: 15px;
            margin: 10px 0;
            font-size: 12px;
            color: #666666;
        }
    }
    .sign-up{
        width: 96%;
        margin: 15px auto;
        height: 40px;
        text-align: center;
        line-height: 40px;
        background: #ffbe00;
        color: #ffffff;
        border-radius: 4px;
        &.cur{
            background: #E6E6E6;
            color: #cccccc;
        }
    }
    .loading{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        &>div{
            width: 112px;
            height: 112px;
            background: rgba(0,0,0,.5);
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            border-radius: 16px;
            &>div:first-child{
                margin-bottom: 5px;
            }
        }
    }
</style>
